import { BASE_URL } from '@/config/myConfiguration.js'
import { getToken } from '@/utils/auth.js'
import { useUserStore } from '@/stores/userStore.js'

// 请求拦截(增强)
function requestInterceptor (config) {
	let { url, method, params, data } = config
	// url 路径
	if (url.indexOf(BASE_URL) === -1) {
		url = BASE_URL + url
	}
	// url 参数
	if (params && typeof params === 'object') {
		let paramsStr = '?'
		Object.keys(params).forEach(k => {
			paramsStr += k + '=' + params[k] + '&'
		})
		url += paramsStr.slice(0, -1)
	}
	// 请求头
	const header = { 
		'Content-Type': 'application/json;charset=utf-8',
		'Authorization': getToken()
	}
	
	return { url, method, data, header }
}

// 响应拦截
function responseInterceptor (response) {
	return new Promise((resolve, reject) => {
		const res = response.data
		if (res.code === 401) {
			useUserStore().resetCurrentDriver()
			
			uni.showToast({ 
				title: '登录状态已过期，请重新登录', 
				icon: 'none', duration: 2000,
				success: () => {
					// #ifdef APP-PLUS
					const pages = getCurrentPages()
					if (pages[pages.length - 1].$getAppWebview()['__uniapp_route'] != 'pages/login-and-register/login') {
						uni.reLaunch({
							url: '/pages/login-and-register/login'
						})
					}
					// #endif
					
					// #ifndef APP-PLUS
					if (window.location.href.split('#')[1] != '/') {
						// console.log(window.location.href)
						uni.reLaunch({
							url: '/pages/login-and-register/login'
						})
					}
					// #endif
				}
			})
			reject(new Error('登录状态已过期，请重新登录'))
		} else if (res.code !== 200) {
			console.log(res)
			uni.showToast({ title: res.message, icon: 'none', duration: 2000 })
			reject(res)
		} else {
			// 放行response
			resolve(res)
		}
	})
}

// http请求
function request (query) {
	// 请求拦截(增强)
	let {
		url,
		method,
		data = {},
		header
	} = requestInterceptor(query);
	// console.log(url)
	
	return new Promise((resolve, reject) => {
		
		uni.request({
			url,
			method,
			data,
			header,
			timeout: 10000,
			// 请求成功
			success: response => {
				// 响应拦截
				responseInterceptor(response).then(res => {
					resolve(res);
				}).catch(e => {
					reject(e);
				});
			},
			// 请求失败
			fail: err => {
				uni.showToast({ title: '系统接口异常', icon: 'none', duration: 2000 })
				reject(err)
			}
		})
	})
}

// 暴露四个方法
export default {
	get ({url, params}) {
		return request({
			url,
			method: 'GET',
			params
		})
	},
	post ({url, params, data}) {
		return request({
			url,
			method: 'POST',
			params,
			data
		})
	},
	put ({url, params, data}) {
		return request({
			url,
			method: 'PUT',
			params,
			data
		})
	},
	delete ({url, params}) {
		return request({
			url,
			method: 'DELETE',
			params
		})
	}
}